#include "SEnumTypeDescriptor.h"

bool SEnumTypeDescriptor::IsValidKey( string key )
{
	regex reg("[a-zA-Z_][0-9a-zA-Z_]+");
	return regex_match(key, reg);
}

void SEnumTypeDescriptor::AddEntry( string value, unsigned long numericValue, string description )
{
	if ( !IsValidKey(value) )
	{
		throw SArgumentException("Invalid key.");
	}
	if ( IsDefined(value) )
	{
		throw SArgumentException("There is an entry with the same key.");
	}
	if ( IsDefined(numericValue) )
	{
		throw SArgumentException("There is an entry with the same value.");
	}

	entries->push_back( SEnumEntry::Create(value, numericValue, description) );
}

unsigned long SEnumTypeDescriptor::GetNumericValue( string value )
{
	BOOST_FOREACH(SEnumEntrySp entry, *entries)
	{
		if ( entry ) 
		{
			if ( entry->GetName() == value )
			{
				return entry->GetNumericValue();
			}
		}
	}

	throw SArgumentException("The key passed is not defined.");
}

string SEnumTypeDescriptor::GetValue( unsigned long numericValue )
{
	BOOST_FOREACH(SEnumEntrySp entry, *entries)
	{
		if ( entry ) 
		{
			if ( entry->GetNumericValue() == numericValue )
			{
				return entry->GetValue();
			}
		}
	}

	throw SArgumentException("The value passed is not defined.");
}

SEnumEntrySp SEnumTypeDescriptor::GetEntry( int index )
{
	if ( index < 0 || index >= (int) entries->size() )
	{
		throw SArgumentException("There is not an entry at this position.");
	}

	return entries->at(index);
}

bool SEnumTypeDescriptor::IsDefined( string value )
{
	BOOST_FOREACH(SEnumEntrySp entry, *entries)
	{
		if ( entry ) 
		{
			if ( entry->GetName() == value )
			{
				return true;
			}
		}
	}

	return false;
}

bool SEnumTypeDescriptor::IsDefined( unsigned long numericValue )
{
	BOOST_FOREACH(SEnumEntrySp entry, *entries)
	{
		if ( entry ) 
		{
			if ( entry->GetNumericValue() == numericValue )
			{
				return true;
			}
		}
	}

	return false;
}

SEnumTypeDescriptorSp SEnumTypeDescriptor::Create( string pluginName, string name, string description )
{
	if ( name.empty() )
	{
		throw SArgumentException("Name cannot be empty.");
	}

	return SEnumTypeDescriptorSp(new SEnumTypeDescriptor(pluginName, name, description));
}